package com.arch.flink.archetype.network.handler;

import org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf;
import org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled;
import org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext;
import org.apache.flink.shaded.netty4.io.netty.channel.ChannelOutboundHandlerAdapter;
import org.apache.flink.shaded.netty4.io.netty.channel.ChannelPromise;

/**
 * @author pizhihui
 * @date 2024-05-20 18:13
 */
public class OutboundEnvelopeEncoder extends ChannelOutboundHandlerAdapter {


    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ByteBuf buf = ctx.alloc().directBuffer();


        // 写入数据
        encode(buf);


        if (buf.isReadable()) {
            ctx.write(buf, promise);
        } else {
            buf.release();
            ctx.write(Unpooled.EMPTY_BUFFER, promise);
        }

    }

    private void encode(ByteBuf out) {
        out.writeBytes("Hello world".getBytes());
    }
}
